package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.QueryMember;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.Setmeal;
import com.itheima.service.MemberService;
import com.itheima.utils.DateUtils;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/member")
public class MemberController {

    @Autowired
    private JedisPool jedisPool;
    @Reference
    private MemberService memberService;

    @RequestMapping("/login.do")
    public Result login(HttpServletResponse response, @RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        try {
            Jedis resource = jedisPool.getResource();
            String validateCodeInRedis = resource.get(telephone + RedisMessageConstant.SENDTYPE_LOGIN); //获取redis验证码
            String countStr = resource.get(telephone + RedisMessageConstant.SENDTYPE_COUNT);       //获取验证码可用次数
            if (validateCode != null && validateCodeInRedis != null && countStr != null
                    && validateCode.equals(validateCodeInRedis) && Integer.parseInt(countStr) > 0) {
                //看看用户是否存在
                Member member = memberService.findByTelephone(telephone);
                //不存在的就注册用户
                if (member == null) {
                    member = new Member();
                    member.setRegTime(new Date());
                    member.setPhoneNumber(telephone);
                    memberService.add(member);
                }
                //保存用户信息到cookies
                //String md5Tele = MD5Utils.md5(telephone);
                Cookie cookie = new Cookie("member_telephone", telephone);
                cookie.setPath("/");
                cookie.setMaxAge(60 * 60 * 24 * 30);
                response.addCookie(cookie);
                //将会员信息保存到redis
                String json = JSON.toJSON(member).toString();
                resource.setex(telephone, 60 * 30, json);
                //删除redis集合中的数据
                resource.del(telephone + RedisMessageConstant.SENDTYPE_COUNT);
                resource.del(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
                //释放资源
                resource.close();
                //成功登录
                return new Result(true, MessageConstant.LOGIN_SUCCESS);
            } else {
                //如果验证码还有验证次数  验证码校验次数减一
                if (countStr != null) {
                    Integer count = Integer.parseInt(countStr);
                    if (count > 0) {
                        resource.setex(telephone + RedisMessageConstant.SENDTYPE_COUNT, 300, String.valueOf(count - 1));
                    }
                }
                resource.close();
                //验证码错误
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
            //登录出错
            return new Result(false, MessageConstant.LOGIN_FAIL);
        }
    }


    @RequestMapping("/findByCookie.do")
    public Result findByCookie(HttpServletRequest request) {
        try {
            String telephone = getCookieTele(request);
            if (telephone == null || telephone.length() == 0) {
                return new Result(false, "登录失效");
            }
            //通过号码查找用户
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                return new Result(false, "登录失效");
            }
            return new Result(true, "个人信息加载成功", member);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "个人信息加载失败");
        }
    }

    //根据Cookie获取用户手机号
    private String getCookieTele(HttpServletRequest request) {
        String telephone = null;
        //获取Cookie信息
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            //获取手机号
            for (int i = 0; i < cookies.length; i++) {
                if (cookies[i].getName().equals("member_telephone")) {
                    //获取手机号
                    telephone = cookies[i].getValue();
                }
            }
        }
        return telephone;
    }


    @RequestMapping("/editInMobile.do")
    public Result editInMobile(@RequestBody Member member) {
        try {
            member.setPhoneNumber(null);
            member.setRegTime(null);
            memberService.editMember(member);
            return new Result(true, "更新个人信息成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "更新个人信息失败");
        }
    }

    //根据手机号码查询对应会员的全部预订信息
    @RequestMapping("/findSetmealByIdAndDate.do")
    public Result findSetmealByIdAndDate(HttpServletRequest request, @RequestBody Map<String, String> orderInfo) {
        try {
            String telephone= getCookieTele (request);
            //String telephone = "18811679442";
            if (telephone != null && telephone.length() > 0) {
                Result  result= memberService.findSetmealByIdAndDate(telephone, orderInfo);
                return result;
            }

            return new Result(false, "查询预约信息失败");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询预约信息失败");
        }
    }

    @RequestMapping("/findMemberById.do")
    public Result findMemberById(Integer id,Integer oid){
        try {
                QueryMember queryMember = memberService.findMemberById(id,oid);
                return new Result(true,"",queryMember);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, "查询预约信息失败");
        }
    }

}
